#include "prec.h"
#include "commanager.h"

template<> wxDComponentManager* wxDSingleton<wxDComponentManager>::msSingleton = NULL;
wxDComponentManager& wxDComponentManager::GetSingleton()
{
	wxASSERT(msSingleton);
	return *msSingleton;
}

wxDComponentManager* wxDComponentManager::GetSingletonPtr()
{
	wxASSERT(msSingleton);
	return msSingleton;
}

wxDComponentManager::wxDComponentManager()
	: wxDSingleton<wxDComponentManager>(COMPONENT_MANAGER_NAME, false)
{
	Add(this);
}

wxDComponentManager::~wxDComponentManager()
{
	DeleteAll();
}

void wxDComponentManager::Add( wxDComponent* component )
{
	if (component->IsManaged())
		return;

	mComDict[component->GetId()] = component;
	component->mManaged = true;
}

void wxDComponentManager::Delete( const wxString& id )
{
	wxASSERT_MSG( id == COMPONENT_MANAGER_NAME, wxT("Component.Manager is system component can't delete"));

	wxDComponentDict::iterator it = mComDict.find(id);

	wxASSERT_MSG(it != mComDict.end(), wxT("not find component in manager"));

	if (it->second)
	{
		delete it->second;
	}
	mComDict.erase(it);
}

void wxDComponentManager::DeleteAll()
{
	for (wxDComponentDict::iterator it = mComDict.begin(); it != mComDict.end(); )
	{
		if (it->first != COMPONENT_MANAGER_NAME)
		{
			if (it->second)
			{
				delete it->second;
			}
			mComDict.erase(it++);
		}
		else
		{
			it++;
		}
	}
}
